<?php
//发放中心/空间利润
namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;


class StoreLirun extends Command
{
    protected function configure()
    {
        $this->setName('store_lirun');
    }

    protected function execute(Input $input, Output $output)
    {
        $time = time();
        $sendStatus = db('store_lirun_log')->where('status','0')->find();
        if (!empty($sendStatus)) {
            exit('等上次发放完成，再进行操作');
        }
        $sendId = db('store_lirun_log')->insertGetId([
            'addtime'=>$time,
            'status'=>0
        ]);
        $day = db('config')->where(['name'=>'lirun_send_day','group'=>'basic'])->value('value');
        $day = $day ? $day : 7;//发放周期
        $sendBetweenTime = $day*86400;
        $maxSendTime = $time-$sendBetweenTime;

        //到周期内未发放的利润
        $lirunLog = db('store_lirun')->where('addtime','<=',$maxSendTime)->where('authen','1')->order('addtime ASC')->select();
    
        foreach ($lirunLog AS $key => $value) {
            Db::startTrans();
            try{
                $logId = $value['id'];
                $storeId = $value['store_id'];
                $lirun = $value['lirun'];
                //更新发放状态
                db('store_lirun')->where('id',$logId)->update([
                    'authen'=>2,
                    'authen_time'=>time()
                ]);
                //余额增加
                $store = db('store')->where('id',$storeId)->lock(true)->find();
                db('store')->where('id',$storeId)->inc('balance',$lirun)->update();

                //新增中心/空间利润账户变动记录
                db('balance_log')->insert([
                    'store_id'=>$storeId,
                    'before_price'=>$store['balance'],
                    'price'=>$lirun,
                    'new_price'=>bcadd($store['balance'],$lirun,2),
                    'type'=>1,
                    'addtime'=>time()
                ]);
                Db::commit();
            }catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                db('store_lirun_log')->where('id',$sendId)->update([
                    'longtime'=>time()-$time,
                    'status'=>2
                ]);
                exit($e->getMessage());
            }
        }
        db('store_lirun_log')->where('id',$sendId)->update([
            'longtime'=>time()-$time,
            'status'=>1
        ]);
        if (empty($lirunLog)) {
            exit('今天没有可发放利润');
        }
        exit('发放利润完成');
    }
}
